<template>
  <div class="product-container">
    <a-card title="商品管理" :bordered="false">
      <!-- 搜索区域 -->
      <div class="search-header">
        <a-form
          :model="searchForm"
          layout="inline"
          class="search-form"
          @finish="handleSearch"
        >
          <a-form-item label="商品名称" name="name">
            <a-input
              v-model:value="searchForm.name"
              placeholder="请输入商品名称"
              style="width: 200px"
              allowClear
            />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" html-type="submit">搜索</a-button>
            <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
            <a-button type="primary" style="margin-left: 8px" @click="showAddModal">添加商品</a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 列表区域 -->
      <a-table
        :columns="columns"
        :data-source="productList"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        rowKey="productId"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'imageUrlList'">
            <div style="display: flex; gap: 8px;">
              <template v-if="record.imageUrlList && record.imageUrlList.length">
                <a-image
                  v-for="(url, index) in record.imageUrlList"
                  :key="index"
                  :width="50"
                  :height="50"
                  :src="url"
                  :preview="true"
                  style="object-fit: cover;"
                />
              </template>
              <template v-else>-</template>
            </div>
          </template>
          <template v-if="column.key === 'create_time'">
            {{ formatDate(record.create_time) }}
          </template>
          <template v-if="column.key === 'update_time'">
            {{ formatDate(record.update_time) }}
          </template>
          <template v-if="column.key === 'coverImage'">
            <a-image
              :width="100"
              :src="record.coverImage"
              :fallback="'https://via.placeholder.com/100'"
            />
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="handleEdit(record)">编辑</a-button>
              <a-button type="link" danger @click="handleDelete(record)">删除</a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 添加商品弹窗 -->
    <a-modal
      v-model:visible="addModalVisible"
      title="添加商品"
      @ok="handleAdd"
      @cancel="handleCancel"
      :confirmLoading="addLoading"
    >
      <a-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        layout="vertical"
      >
        <a-form-item label="商品名称" name="name">
          <a-input v-model:value="addForm.name" placeholder="请输入商品名称" />
        </a-form-item>
        <a-form-item label="商品描述" name="description">
          <a-textarea v-model:value="addForm.description" placeholder="请输入商品描述" />
        </a-form-item>
        <a-form-item label="分类" name="categoryId">
          <a-tree-select
            v-model:value="addForm.categoryId"
            style="width: 100%"
            :tree-data="categoryTreeData"
            placeholder="请选择分类"
            :loading="categoryLoading"
            :field-names="{
              label: 'name',
              value: 'id',
              children: 'child'
            }"
            show-search
            tree-default-expand-all
          />
        </a-form-item>
        <a-form-item label="基础价格" name="basePrice">
          <a-input-number v-model:value="addForm.basePrice" placeholder="请输入基础价格" style="width: 100%" :min="0" :precision="2" />
        </a-form-item>
        <a-form-item label="商品图片" name="imageList">
          <a-upload
            v-model:file-list="fileList"
            :before-upload="beforeUpload"
            :maxCount="5"
            list-type="picture-card"
            @change="handleChange"
            :show-upload-list="true"
            :customRequest="customRequest"
          >
            <div v-if="fileList.length < 5">
              <plus-outlined />
              <div style="margin-top: 8px">上传</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="排序" name="sort">
          <a-input-number v-model:value="addForm.sort" placeholder="请输入排序" style="width: 100%" :min="0" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 编辑商品弹窗 -->
    <a-modal
      v-model:visible="editModalVisible"
      title="编辑商品"
      @ok="handleEditSubmit"
      @cancel="handleEditCancel"
      :confirmLoading="editLoading"
    >
      <a-form
        :model="editForm"
        :rules="addFormRules"
        ref="editFormRef"
        layout="vertical"
      >
        <a-form-item label="商品名称" name="name">
          <a-input v-model:value="editForm.name" placeholder="请输入商品名称" />
        </a-form-item>
        <a-form-item label="商品描述" name="description">
          <a-textarea v-model:value="editForm.description" placeholder="请输入商品描述" />
        </a-form-item>
        <a-form-item label="分类" name="categoryId">
          <a-tree-select
            v-model:value="editForm.categoryId"
            style="width: 100%"
            :tree-data="categoryTreeData"
            placeholder="请选择分类"
            :loading="categoryLoading"
            :field-names="{
              label: 'name',
              value: 'id',
              children: 'child'
            }"
            show-search
            tree-default-expand-all
          />
        </a-form-item>
        <a-form-item label="基础价格" name="basePrice">
          <a-input-number v-model:value="editForm.basePrice" placeholder="请输入基础价格" style="width: 100%" :min="0" :precision="2" />
        </a-form-item>
        <a-form-item label="商品图片" name="imageList">
          <a-upload
            v-model:file-list="editFileList"
            :before-upload="beforeUpload"
            :maxCount="5"
            list-type="picture-card"
            @change="handleEditChange"
            :show-upload-list="true"
            :customRequest="customEditRequest"
          >
            <div v-if="editFileList.length < 5">
              <plus-outlined />
              <div style="margin-top: 8px">上传</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="排序" name="sort">
          <a-input-number v-model:value="editForm.sort" placeholder="请输入排序" style="width: 100%" :min="0" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { listAllProduct, addProduct, delProduct, modifyProduct } from '@/api/product';
import { listAllCategory } from '@/api/category';
import { message, TreeSelect } from 'ant-design-vue';
import type { TablePaginationConfig } from 'ant-design-vue';
import dayjs from 'dayjs';
import type { FormInstance } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { uploadFile } from '@/api/file';
import type { UploadProps } from 'ant-design-vue';

interface Product {
  productId: number;
  name: string;
  description: string;
  category_id: number;
  basePrice: number;
  imageUrlList: string[];
  sort: number;
  create_time: string;
  update_time: string;
  coverImage: string;
}

// 搜索表单
const searchForm = reactive({
  pageSize: 10,
  pageNum: 1,
  name: ''
});

// 商品列表
const productList = ref<Product[]>([]);
const loading = ref(false);

// 分页配置
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  onChange: (page: number, pageSize: number) => {
    searchForm.pageNum = page;
    searchForm.pageSize = pageSize;
    loadProductList();
  }
});

// 在 script 部分添加分类数据存储
const categoryMap = ref<Map<number, string>>(new Map());

// 表格列配置
const columns = [
  {
    title: '商品名称',
    dataIndex: 'name',
    key: 'name',
    width: 200
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true
  },
  {
    title: '分类',
    dataIndex: 'category_id',
    key: 'category_id',
    width: 150,
    customRender: ({ text }: { text: number }) => categoryMap.value.get(text) || '-'
  },
  {
    title: '图片',
    dataIndex: 'imageUrlList',
    key: 'imageUrlList',
    width: 200
  },
  {
    title: '创建时间',
    dataIndex: 'create_time',
    key: 'create_time',
    width: 180
  },
  {
    title: '更新时间',
    dataIndex: 'update_time',
    key: 'update_time',
    width: 180
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right'
  }
];

// 页面初始化
onMounted(() => {
  console.log('商品管理页面初始化');
  loadCategoryList();  // 先加载分类数据
  loadProductList();   // 再加载商品列表
});

// 加载商品列表
const loadProductList = async () => {
  loading.value = true;
  try {
    console.log('开始加载商品列表，参数:', {
      pageSize: searchForm.pageSize,
      pageNum: searchForm.pageNum,
      name: searchForm.name
    });
    const res = await listAllProduct(
      searchForm.pageSize,
      searchForm.pageNum,
      searchForm.name
    );
    console.log('商品列表数据:', res);
    if (res.data.code === 200) {
      productList.value = res.data.data.list || [];
      pagination.total = res.data.data.total || 0;
      pagination.current = res.data.data.pageNum || 1;
      pagination.pageSize = res.data.data.pageSize || 10;
    } else {
      message.error(res.data.msg || '获取商品列表失败');
    }
  } catch (error) {
    console.error('获取商品列表失败:', error);
    message.error('获取商品列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  searchForm.pageNum = 1;
  loadProductList();
};

// 处理重置
const handleReset = () => {
  // 清空搜索表单数据
  searchForm.name = '';
  searchForm.pageNum = 1;
  searchForm.pageSize = 10;
  // 重新加载商品列表
  loadProductList();
};

// 处理表格变化
const handleTableChange = (pag: TablePaginationConfig) => {
  searchForm.pageNum = pag.current || 1;
  searchForm.pageSize = pag.pageSize || 10;
  loadProductList();
};

// 格式化日期
const formatDate = (date: string) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '-';
};

// 添加商品弹窗
const addModalVisible = ref(false);
const addLoading = ref(false);
const addFormRef = ref<FormInstance>();

// 添加表单
const addForm = reactive({
  name: '',
  description: '',
  categoryId: undefined as number | undefined,
  basePrice: undefined as number | undefined,
  imageList: [] as string[],
  sort: undefined as number | undefined
});

// 添加表单验证规则
const addFormRules = {
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入商品描述', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }],
  basePrice: [{ required: true, message: '请输入基础价格', trigger: 'blur' }],
  imageList: [{ 
    required: true, 
    message: '请上传商品图片', 
    trigger: ['change', 'submit'],
    validator: (rule: any, value: any) => {
      console.log('验证imageList:', value);
      if (!value || value.length === 0) {
        return Promise.reject('请上传商品图片');
      }
      return Promise.resolve();
    }
  }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
};

// 分类树数据
const categoryTreeData = ref<any[]>([]);
const categoryLoading = ref(false);

// 修改加载分类列表的方法
const loadCategoryList = async () => {
  categoryLoading.value = true;
  try {
    const res = await listAllCategory();
    console.log('API返回数据:', res);
    if (res.data.code === 200) {
      const categories = res.data.data || [];
      if (categories.length === 0) {
        message.warning('暂无分类数据');
      }
      categoryTreeData.value = categories;
      // 构建分类ID到名称的映射
      const buildCategoryMap = (items: any[]) => {
        items.forEach(item => {
          categoryMap.value.set(item.id, item.name);
          if (item.child && item.child.length > 0) {
            buildCategoryMap(item.child);
          }
        });
      };
      buildCategoryMap(categories);
    } else {
      message.error(res.data.msg || '获取分类列表失败');
    }
  } catch (error) {
    console.error('获取分类列表失败:', error);
    message.error('获取分类列表失败，请稍后重试');
  } finally {
    categoryLoading.value = false;
  }
};

// 显示添加弹窗
const showAddModal = () => {
  addModalVisible.value = true;
  loadCategoryList();
};

// 处理添加商品
const handleAdd = async () => {
  try {
    await addFormRef.value?.validate();
    addLoading.value = true;
    
    const res = await addProduct({
      name: addForm.name,
      description: addForm.description,
      categoryId: addForm.categoryId || 0,
      basePrice: addForm.basePrice || 0,
      imageList: addForm.imageList,
      sort: addForm.sort || 0
    });

    if (res.data.code === 200) {
      message.success('添加成功');
      addModalVisible.value = false;
      // 重置表单
      Object.assign(addForm, {
        name: '',
        description: '',
        categoryId: undefined,
        basePrice: undefined,
        imageList: [],
        sort: undefined
      });
      // 清空文件列表
      fileList.value = [];
      // 刷新列表
      loadProductList();
    } else {
      message.error(res.data.msg || '添加失败');
    }
  } catch (error) {
    console.error('添加商品失败:', error);
    message.error('添加失败，请稍后重试');
  } finally {
    addLoading.value = false;
  }
};

// 处理取消添加
const handleCancel = () => {
  addModalVisible.value = false;
  addFormRef.value?.resetFields();
  fileList.value = [];
};

// 编辑商品相关
const editModalVisible = ref(false);
const editLoading = ref(false);
const editFormRef = ref<FormInstance>();
const editFileList = ref<any[]>([]);

const editForm = reactive({
  productId: 0,
  name: '',
  description: '',
  categoryId: undefined as number | undefined,
  basePrice: undefined as number | undefined,
  imageList: [] as string[],
  sort: undefined as number | undefined
});

// 处理编辑按钮点击
const handleEdit = (record: Product) => {
  editModalVisible.value = true;
  // 加载分类数据
  loadCategoryList();
  // 设置表单数据
  Object.assign(editForm, {
    productId: record.productId,
    name: record.name,
    description: record.description,
    categoryId: record.category_id,
    basePrice: Number(record.basePrice) || 0,  // 确保转换为数字
    imageList: record.imageUrlList || [],
    sort: record.sort
  });
  // 设置文件列表
  editFileList.value = (record.imageUrlList || []).map((url: string, index: number) => ({
    uid: `-${index}`,
    name: `image-${index}`,
    status: 'done',
    url: url
  }));
};

// 处理编辑提交
const handleEditSubmit = async () => {
  try {
    await editFormRef.value?.validate();
    editLoading.value = true;
    
    const res = await modifyProduct({
      productId: editForm.productId,
      name: editForm.name,
      description: editForm.description,
      categoryId: editForm.categoryId || 0,
      basePrice: editForm.basePrice || 0,
      imageList: editForm.imageList,
      sort: editForm.sort || 0
    });

    if (res.data.code === 200) {
      message.success('修改成功');
      editModalVisible.value = false;
      // 刷新列表
      loadProductList();
    } else {
      message.error(res.data.msg || '修改失败');
    }
  } catch (error) {
    console.error('修改商品失败:', error);
    message.error('修改失败，请稍后重试');
  } finally {
    editLoading.value = false;
  }
};

// 处理编辑取消
const handleEditCancel = () => {
  editModalVisible.value = false;
  editFormRef.value?.resetFields();
  editFileList.value = [];
};

// 编辑时的自定义上传方法
const customEditRequest = async ({ file, onSuccess, onError }: any) => {
  try {
    const res = await uploadFile(file);
    if (res.data.code === 200) {
      onSuccess(res.data.data);
      editForm.imageList.push(res.data.data.url);
      // 手动触发表单验证
      editFormRef.value?.validateFields(['imageList']);
      message.success('图片上传成功');
    } else {
      onError(new Error(res.data.msg || '图片上传失败'));
    }
  } catch (error) {
    console.error('图片上传失败:', error);
    onError(error);
    message.error('图片上传失败，请稍后重试');
  }
};

// 编辑时的文件变化处理
const handleEditChange: UploadProps['onChange'] = ({ fileList: newFileList, file }) => {
  editFileList.value = newFileList;
  if (file.status === 'removed') {
    // 当图片被删除时，从imageList中移除对应的URL
    const index = editForm.imageList.indexOf(file.url || '');
    if (index > -1) {
      editForm.imageList.splice(index, 1);
      // 手动触发表单验证
      editFormRef.value?.validateFields(['imageList']);
    }
  }
};

// 处理删除
const handleDelete = async (record: Product) => {
  try {
    const res = await delProduct(record.productId);
    if (res.data.code === 200) {
      message.success('删除成功');
      loadProductList();
    } else {
      message.error(res.data.msg || '删除失败');
    }
  } catch (error) {
    console.error('删除商品失败:', error);
    message.error('删除失败，请稍后重试');
  }
};

// 文件上传相关
const fileList = ref<any[]>([]);

const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    message.error('只能上传图片文件！');
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片必须小于2MB！');
    return false;
  }
  return true;
};

// 自定义上传方法
const customRequest = async ({ file, onSuccess, onError }: any) => {
  try {
    const res = await uploadFile(file);
    if (res.data.code === 200) {
      onSuccess(res.data.data);
      addForm.imageList.push(res.data.data.url);
      // 手动触发表单验证
      addFormRef.value?.validateFields(['imageList']);
      message.success('图片上传成功');
    } else {
      onError(new Error(res.data.msg || '图片上传失败'));
    }
  } catch (error) {
    console.error('图片上传失败:', error);
    onError(error);
    message.error('图片上传失败，请稍后重试');
  }
};

const handleChange: UploadProps['onChange'] = ({ fileList: newFileList, file }) => {
  fileList.value = newFileList;
  if (file.status === 'removed') {
    // 当图片被删除时，从imageList中移除对应的URL
    const index = addForm.imageList.indexOf(file.url || '');
    if (index > -1) {
      addForm.imageList.splice(index, 1);
      // 手动触发表单验证
      addFormRef.value?.validateFields(['imageList']);
    }
  }
};
</script>

<style scoped>
.product-container {
  padding: 24px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.search-form {
  flex: 1;
  margin-right: 16px;
}

:deep(.ant-table) {
  margin-top: 16px;
}
</style>
